import React, { useEffect, useState } from 'react';
import { Outlet, Navigate } from 'react-router-dom';
import { getUserInfo } from '@/apis/getUserInfo';
import { CircularProgress, Box } from '@mui/material';

const AdminGuard = () => {
  const [isAdmin, setIsAdmin] = useState(null);

  useEffect(() => {
    const checkAdminStatus = async () => {
      try {
        const userInfo = await getUserInfo();
        setIsAdmin(userInfo.role === 1);
      } catch (error) {
        console.error('获取用户信息失败:', error);
        setIsAdmin(false);
      }
    };

    checkAdminStatus();
  }, []);

  if (isAdmin === null) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" height="100vh">
        <CircularProgress />
      </Box>
    );
  }

  return isAdmin ? <Outlet /> : <Navigate to="/" replace />;
};

export default AdminGuard;